﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;

using SharedGenomics.Core;
using SharedGenomics.Domain;

namespace SharedGenomics.Workbench.PresentationModel
{
    public class DataColumnSchemaFactory : IDataColumnSchemaFactory
    {
        private IDictionary<Type, string> _defaultTypeFormats;

        public DataColumnSchemaFactory()
        {
            this._defaultTypeFormats = new Dictionary<Type, string>();
        }

        public AnalysisResultDataColumnSchema GetColumnSchemaForType(Type t)
        {
            t.ThrowIfNull("t");

            AnalysisResultDataColumnSchema schema = new AnalysisResultDataColumnSchema(t);

            //get all properties and associated ColumnDisplayAttributes
            var columns = from p in t.GetProperties()
                          let displayAtts = p.GetCustomAttributes(typeof(ColumnDisplayAttribute), true)
                          where displayAtts.Length > 0
                          orderby ((ColumnDisplayAttribute)displayAtts[0]).Position
                          select new { Att = (ColumnDisplayAttribute)displayAtts[0], Prop = p };

            foreach (var column in columns)
            {
                Type columnType = column.Prop.PropertyType;
                string defaultFormat = this._defaultTypeFormats.ContainsKey(columnType) ? this._defaultTypeFormats[columnType] : null;

                string format = column.Att.Format ?? defaultFormat;

                DataGridColumnInfo colInfo = new DataGridColumnInfo(column.Att.HeaderText, column.Prop.Name, column.Prop.PropertyType)
                {
                    Format = format
                };

                schema.Add(colInfo);
            }

            return schema;
        }

        public void SetColumnTypeDefaultFormat<T>(string format)
        {
            this._defaultTypeFormats[typeof(T)] = format;
        }
    }
}
